import React, { useState, useEffect } from 'react';
import { Card, Button, Form, Input, Select, Space, Pagination, Spin, Empty, List, message, Tag } from 'antd';
import { SearchOutlined, ReadOutlined, EyeOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { FilterCard, InfoCard } from '@/components/common';
import { questionService } from '@/services/questionService';
import { Question, QuestionListResponse, QuestionType } from '@/types/question';
import { QUESTION_TYPE_OPTIONS, QUESTION_TYPE_MAP, DIFFICULTY_MAP, DIFFICULTY_OPTIONS, getMappingItem } from '@/utils/mappings';
import SingleChoiceQuestion from '@/pages/share/question/components/SingleChoiceQuestion';
import MultipleChoiceQuestion from '@/pages/share/question/components/MultipleChoiceQuestion';
import TrueFalseQuestion from '@/pages/share/question/components/TrueFalseQuestion';
import CodeReadingQuestion from '@/pages/share/question/components/CodeReadingQuestion';

const { Option } = Select;

const QuestionList: React.FC = () => {
  const [questions, setQuestions] = useState<Question[]>([]);
  const [loading, setLoading] = useState(false);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [form] = Form.useForm();
  const navigate = useNavigate();

  // 获取问题列表
  const fetchQuestions = async (page = currentPage, pageSize = 10) => {
    try {
      setLoading(true);
      const params = {
        ...form.getFieldsValue(),
        page,
        page_size: pageSize
      };
      
      const response = await questionService.getQuestions(params);
      if (response.data?.code === 200) {
        const data = response.data.data as unknown as QuestionListResponse;
        setQuestions(data.results);
        setTotal(data.count);
      }
    } catch (error) {
      message.error('获取题目列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchQuestions();
  }, [currentPage, pageSize]);

  // 处理页码变化
  const handlePageChange = (page: number, newPageSize?: number) => {
    setCurrentPage(page);
    if (newPageSize && newPageSize !== pageSize) {
      setPageSize(newPageSize);
    }
  };

  // 处理表单提交
  const handleSearch = () => {
    setCurrentPage(1); // 重置到第一页
    fetchQuestions(1, pageSize);
  };

  // 处理表单重置
  const handleReset = () => {
    form.resetFields();
    setCurrentPage(1);
    fetchQuestions(1, pageSize);
  };
  
  // 开始练习
  const handlePractice = (questionId: number) => {
    navigate(`/question/practice/${questionId}`);
  };

  // 问题类型选项
  const questionTypes = QUESTION_TYPE_OPTIONS;

  const renderQuestion = (question: Question) => {
    switch (question.type) {
      case 'single':
        return <SingleChoiceQuestion question={question} readOnly />;
      case 'multiple':
        return <MultipleChoiceQuestion question={question} readOnly />;
      case 'true_false':
        return <TrueFalseQuestion question={question} readOnly />;
      case 'code_reading':
        return <CodeReadingQuestion question={question} readOnly />;
      default:
        return null;
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await questionService.deleteQuestion(id);
      message.success('删除成功');
      fetchQuestions();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const columns = [
    {
      title: '题目',
      dataIndex: 'content',
      key: 'content',
      render: (_: string, record: Question) => renderQuestion(record),
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: QuestionType) => {
        const { text, color } = getMappingItem(QUESTION_TYPE_MAP, type);
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '难度',
      dataIndex: 'difficulty',
      key: 'difficulty',
      width: 100,
      render: (difficulty: number) => {
        const { text, color } = getMappingItem(DIFFICULTY_MAP, difficulty.toString());
        return <Tag color={color}>{text}</Tag>;
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: Question) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => navigate(`/client/question/edit/${record.id}`)}
          >
            编辑
          </Button>
          <Button
            type="link"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
          >
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <FilterCard
        pageTitle="题目库"
        titleIcon={<ReadOutlined />}
        form={form}
        onFinish={handleSearch}
        onReset={handleReset}
      >
        <Form.Item name="type" label="类型">
          <Select style={{ width: 120 }} allowClear placeholder="选择题目类型">
            {questionTypes.map(type => (
              <Option key={type.value} value={type.value}>{type.label}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="difficulty" label="难度">
          <Select style={{ width: 120 }} allowClear placeholder="选择难度">
            {DIFFICULTY_OPTIONS.map(option => (
              <Option key={option.value} value={option.value}>
                {option.label}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item name="search" label="关键词">
          <Input placeholder="题目内容关键词" />
        </Form.Item>
      </FilterCard>

      <InfoCard>
        <Spin spinning={loading}>
          {questions.length > 0 ? (
            <List
              dataSource={questions}
              renderItem={(question) => (
                <List.Item 
                  key={question.id}
                  actions={[
                    <Button 
                      key="practice" 
                      type="primary" 
                      icon={<ReadOutlined />}
                      onClick={() => handlePractice(question.id)}
                    >
                      开始练习
                    </Button>
                  ]}
                >
                  <div style={{ width: '100%' }}>
                    {renderQuestion(question)}
                  </div>
                </List.Item>
              )}
            />
          ) : (
            <Empty description="暂无题目" />
          )}

          {/* 分页器 */}
          {total > 0 && (
            <div style={{ padding: '16px 0', textAlign: 'center' }}>
              <Pagination
                current={currentPage}
                pageSize={pageSize}
                total={total}
                showSizeChanger
                showQuickJumper
                showTotal={(total) => `共 ${total} 题`}
                onChange={handlePageChange}
              />
            </div>
          )}
        </Spin>
      </InfoCard>
    </div>
  );
};

export default QuestionList; 